/**
** 地区组件 渲染的全部逻辑
**/
define(['../model/data','./service'],function(DATA,http){

    return function(node,index,data){
        //countries:[],cities:[],locationType:1,isClude:true
        var nodeId = "Location";
        node = node||$("#"+id+" .user-body>li:first");
        var isClude = true;////
        var cType = "country";//默认搜索额 type
        /***
        **检查是否超过了25个限制
        **/
        function checkCount(){
            var len = node.find("ul.select2-selection__rendered").children().length;
            if(len>26){
                node.find("p.loc-alert-msg").text("每组最多只能输入25个国家,请进行调整[当前数："+(len-1)+"]");
                node.find(".loc-alert").css("display","block");
            }else{
                node.find(".loc-alert").removeAttr("style");
            }
        }
        node.find("div.clu-drop").empty().bootDrop({
              list:[{value:0,label:I18N.getText('createAd','exclude')},{value:1,label:I18N.getText('createAd','include')}],
              prop:"label",
              value:1
        }).on("selectChanged",function(e,o){
            isClude = (o.data.value)?true:false;
            kit.addBorderGreen($(e.target).parents('.alert-dismissible').parent());
        });

        //国家，城市，下拉框
        node.find("div.cou-drop").empty().bootDrop({
              list:[{value:"0",label:"Country"},{value:"1",label:"City"}],
              prop:"label",
              value:0
        }).on("selectChanged",function(e,o){
             cType = o.data.label.toLowerCase();
             kit.addBorderGreen($(e.target).parents('.alert-dismissible').parent());
        });

        var rType = DATA.cache.adPublishConditionDetailCache.regionType;
         var fa = node.find("div.magic-content").empty();
        if(rType=="global"){
            var gdata = DATA["global"][0];
            var keys = Object.keys(gdata);
            var excludeKeys = DATA.cache.adPublishConditionDetailCache.excludeKeys;

            for(var i=0;i<keys.length;i++){
                var key = keys[i];
                var arr = gdata[key];
                "+I18N.getText('createAd','unitPrice')+"
                var hd = $("<h4>"+(key=="location"? I18N.getText('createAd', 'accordingAddress'): I18N.getText('createAd', 'accordingLanguage'))+"</h4>");
                fa.append(hd);
                var ul = $("<ul data-type='global'>");
                for(var j=0;j<arr.length;j++){
                    var o = arr[j];
                    var id = o.key||o.countryCode;
                    if(excludeKeys &&excludeKeys.length >0){

                        var isFound = false;
                        for(var i = 0 ; i < excludeKeys.length ; i++){
                            if(id== excludeKeys[i]){
                                isFound = true;
                            }
                        }

                        if(!isFound){
                            var li = $("<li data-value="+id+" data-title='country'>\
                               <label><input type='checkbox'>"+o.name+"</label></li>");
                            ul.append(li);
                        }

                    } else {
                        var li = $("<li data-value="+id+" data-title='country'>\
                               <label><input type='checkbox'>"+o.name+"</label></li>");
                        ul.append(li);
                    }
                }
                fa.append(ul);
            }
        }else{  //投放控制里面的国家
            var inData = DATA.cache.adPublishConditionDetailCache.regionAndPrices.include;
            for(var i=0;i<inData.length;i++){
                hd = $("<h4><label><input type='checkbox'>"+I18N.getText('createAd','unitPrice')+" $"+inData[i].price+"</label></h4>");
                fa.append(hd);
                (function(hd){
                    hd.find("input[type]").unbind("change").change(function(e){
                        e.stopImmediatePropagation();
                        if($(this).prop("checked")){
                            $(this).parents("h4").next("ul").find("input[type]").prop("checked",true);
                        }else{
                            $(this).parents("h4").next("ul").find("input[type]").prop("checked",false);
                        }
                    });
                }(hd));
                var arr = inData[i].region;
                var ul = $("<ul data-type='include'>");
                for(var n=0;n<arr.length;n++){
                    var o = arr[n];
                    if(!o) continue;
                    var title = o.type||o.cType||"country";
                    var id = o.key||o.countryCode;
                    var text;
                    if(title == 'country'){
                        text = o.name + '('+id+ ')'
                    } else {
                        text =  o.name;
                    }
                    var li = $("<li data-value="+id+" data-title="+title+" c-name='" + o.name + "'>\
                               <label><input type='checkbox'>"+text+"</label></li>");
                    ul.append(li);
                }
                fa.append(ul);
            }
        }
        //魔法棒点击
        node.find("i.fa-text:first").unbind("click").click(function(e){
            e.stopImmediatePropagation();
            $('.cou-drop').removeClass('open');
            var ta = node.find("div.loc-magic-drop:first");
            ta.find("input[type=checkbox]:checked").prop("checked",false);
            if(ta.hasClass("hidden")){
                ta.removeClass("hidden")
            }else{
                ta.addClass("hidden");
            }

        });
        node.find("div.loc-magic-drop:first").click(function(e){
            e.stopImmediatePropagation();
        });


        /**
         *  过滤掉投放控制中不投放的地区
         * @param result
         * @returns {*}
         */
        this.filterFun = function (result){
            if(DATA.cache&&DATA.cache.adPublishConditionDetailCache&&DATA.cache.adPublishConditionDetailCache.excludeKeys){
                var  excludeKeys = DATA.cache.adPublishConditionDetailCache.excludeKeys, resultArray = [];
                if(excludeKeys &&excludeKeys.length >0){
                    $.each(result,function(i,v){
                        var isFound = false;
                        for(var i = 0 ; i < excludeKeys.length ; i++){
                            if(v.id == excludeKeys[i]){
                                isFound = true;
                            }
                        }

                        if(!isFound){
                            resultArray.push(v);
                        }
                    })
                    return resultArray;
                } else{
                    return result;
                }
            } else {
                return result;
            }
        }

        node.find("button.magic-ok").unbind("mousedown").mousedown(function(e){
            e.stopImmediatePropagation();
            var _this = this;
            $(this).parent().addClass("hidden");
            var type = $(this).parent().find("ul").data("type");
            var values = [];
            //将遗留的国家和城市清理掉
            data.countries=[]; data.cities=[];
            var excludeKeys = DATA.cache.adPublishConditionDetailCache.excludeKeys;
            if(type=="global"){// 按地区，按语言
                $(this).parent().find("ul>li:has(input:checked)").each(function(idx,item){
                    var key = $(item).data("value");
                    var region = kit.region(DATA.global[0].location.concat(DATA.global[0].lang),key);
                    for(var i=0;i<region.length;i++){
                        var the = region[i];
                        var o = {
                            "id":the.countryCode,
                            "key":the.countryCode,
                            "countryCode":the.countryCode,
                            "text":the.name+'('+the.countryCode+')',
                            "name":the.name,
                            "type":$(item).data('title'),
                            "cType":$(item).data('title'),
                            "isClude":isClude
                        }
                        var tag = (o.type=="country")?"countries":"cities";
                        if(kit.objectIn(data[tag],o,"id") == -1 && -1 == excludeKeys.indexOf(o.id)){
                            //将投放控制中的不投放地区排除掉
                            values.push(o);
                            data[tag].push(o);
                        }
                    }
                });
            }else{//按单价
                $(this).parent().find("ul>li:has(input:checked)").each(function(idx,item){
                   o = {"id":$(item).data("value"),
                                 "key":$(item).data("value"),
                                 "countryCode":$(item).data("value"),
                                 "type":$(item).data("title"),
                                 "cType":$(item).data("title"),
                                 "text":$(item).text().trim(),
                                 "name":$(item).attr("c-name"),
                                 "isClude":isClude
                                };
                    var tag = ((o.type||o.title)=="country")?"countries":"cities";
                    if(kit.objectIn(data[tag],o,"id") == -1 && -1 == excludeKeys.indexOf(o.id)){
                        //将投放控制中的不投放地区排除掉
                        values.push(o);
                        data[tag].push(o);
                    }
                });
            }

            //清理之前选择框中
            var nodeIndex = node.attr("index");
            node.find("select.cs-search-ins").empty();
            //增加本次选中
            if(values.length){
                kit.setTags($(this).parent().siblings("select"),values);
                DATA.update(nodeId,nodeIndex,data);
            } else {
                DATA.delItem(nodeId,nodeIndex);
            }
            checkCount();
            bindKeyDown();
        });

        $(document).click(function(e){
            node.find("div.loc-magic-drop:first").addClass("hidden");
            node.find(".magic-content input[type=checkbox]:checked").prop("checked",false);
        });

        node.find("div.peo-group").empty().bootDrop({
            list:[{value:1,text:I18N.getText('createAd','peopleAllHere')},{value:2,text:I18N.getText('createAd','peopleLiveInHere')},
                  {value:3,text:I18N.getText('createAd','peopleRecentlyHere')},{value:4,text:I18N.getText('createAd','peopleTravelingHere')}],
            prop:"text",
            value:(data.locationType&&data.locationType-1)||0  //表示是第几个，不是值
        }).on("selectChanged",function(e,o){
            data.locationType = o.data.value;
            var nodeIndex = node.attr("index");
            DATA.update(nodeId,nodeIndex,data);
        });
        //输入文字后搜索
        var locSelect = node.find("select.cs-search-ins");
        //处理 window  backspace 键盘点击，删除一个tag的问题
        locSelect.empty().select2({
             ajax:http.s2AJAX("/search/searchAdgeolocation",{
                 //cType:cType||"country",
                 locale:I18N.language,
                 //isClude:isClude,
                 excludeKeys:[]
             }, {
                 idkey: "key", textkey: "name", isClude: isClude,
                 textFun: function (obj) {
                     if ('country' == obj.type){
                         return obj.name + "(" + obj.countryCode + ")";
                     } else {
                         return obj.name;
                     }
                 },
                 // 每次请求后台额外增加的参数
                 extParams: function(){ //查询请求时候默认携带参数
                    return {
                        cType:cType||"country",
                        isClude: isClude ? 1 : 0
                    }
                 },
                 //每个结果给增加额外的属性
                 extProcessResults: function(obj){
                     obj.isClude = isClude;
                     obj.type = cType||"country";
                     return obj;
                 },
                 ///对返回回来的结果进行过滤处理
                 filterFun: filterFun
             }),
                minimumInputLength: 1,
                placeholder: I18N.getText('createAd','pleaseSelectRegion'),
//                tokenSeparators: [',', ' '],
                multiple:true,
                templateSelection:function(selection){
                    //通过魔法棒选择国家,主要是现实错误
                    if(selection.isClude == undefined){
                        //模板导入
                        var element = selection.element;
                        selection.isClude  = $(element).data('isclude');
                    }
                    if (selection.isClude == undefined){
                        selection.isClude = isClude;
                    }
                    var text;
                    if(selection.isClude){
                        text = selection.text+  " ["+ I18N.getText('createAd','include') +"]";
                    } else {
                        text = selection.text+ " [" + I18N.getText('createAd','exclude') +"]";
                    }
                    return text;
                }
        }).off("select2:select").on("select2:select",function(e){
            var o = e.params.data;
            if(!data.countries){data.countries=[]; data.cities=[]};
            o.cType = o.type;
            data[(o.type=="country")?"countries":"cities"].push(o);
            var nodeIndex = node.attr("index");
            DATA.update(nodeId,nodeIndex,data);
            checkCount();
            bindKeyDown();
        }).off("select2:unselect").on("select2:unselect",function(e){
            var o = e.params.data,element = e.params.data.element;
            o.type = o.type || $(element).data('type');
            if(!data.countries) { data.countries=[];data.cities = [];  }
            var tag = ((o.type||o.title)=="country")?"countries":"cities";
            var idx = kit.find(data[tag],e.params.data,"id","id");//arr,object,key
            data[tag].splice(idx,1);
            var nodeIndex = node.attr("index");
            DATA.update(nodeId,nodeIndex,data);
            locSelect.find("option[value="+o.id+"]").remove();
            checkCount();
			bindKeyDown();  //select2 4.0 unselect事件对原事件可能有销毁  需要在unselect 后再次进行绑定keydown
        }).off("select2:selecting").on('select2:selecting',function(e){
            //判断投放控制
            var isAllow = false,o = e.params.args.data,
                inData = DATA.cache.adPublishConditionDetailCache.regionAndPrices.include;
            if(inData&&inData.length>0){ //inData为空的话，就当作没有设置国家
                var code = o.key||o.countryCode;
                if (DATA.cache.adPublishConditionDetailCache.includeKeys.indexOf(code) !=  -1){
                    isAllow = true;
                }
            } else {
                isAllow = true;
            }

            if(!isAllow){
                var deLoc = DATA.cache.adPublishConditionDetailCache.includeValue.join(",");
                //暂时没有好用的提示，先用这个吧。
                kit.alert3(I18N.getText('createAd', 'lnlySelectDesignatedLocation', deLoc));
            }
            return isAllow;
        })
        //复制黏贴功能
		//@baukh20151016:如果后期发现插件直接可以实现的方式 请调整
		//select2 4.0 DataAdapter 报错 引用full.min.js同样出错
		//select2 4.0 对keydown有清除冒泡动作 所以需要延时绑定keydown  用托管事件不起作用
		//select2 4.0 unselect事件对原事件可能有销毁  需要在unselect 后再次进行绑定keydown
		//#copy begin
		var isCtrlKey = false,
			isCopy = false;
		window.setTimeout(function(){
			bindKeyDown();
		},1000);
        if($('.select2-search__field').length != 0){

        }
        $('.select2-search__field').get(0).oncontextmenu = function(){
            return false;
        }
		var selectWrapper = $(locSelect.parent());
		function bindKeyDown(){
			$('.select2-search__field', selectWrapper).off("keydown").on('keydown', function(e){
				if(e.ctrlKey|| e.metaKey){
					isCtrlKey = true;
					window.setTimeout(function(){
						isCtrlKey = false;
					},500);
				}
				if(isCtrlKey && e.keyCode == 86){
					isCopy = true;
					locSelect.select2('close');
				}
			});
		}
		selectWrapper.on('keyup', function(e){

			if(!isCopy){
				return;
			}
			var _input = $('.select2-search__field', this);
			if(_input.val() == ''){
				return;
			}
		//	locSelect.val(dataArray).trigger("change");
            var body = {countries: _input.val() || '',
                isClude: isClude ? 1 : 0,
                locale:I18N.language,
                excludeKeys : ["CM","CN"]}
            http.do("/search/searchAdgeolocationList",
                {param:JSON.stringify(body)}).then(function(res){
                    var tempData = {};
                    var c_ids = [];
                    var selectData = locSelect.select2("data");
                    $(locSelect.select2("data")).each(function(i){
                        c_ids.push(selectData[i].id);
                    });
                    $(res.data).each(function(i,dd){
                        if($.inArray(res.data[i].countryCode, c_ids) == -1){
                            c_ids.push(res.data[i].countryCode);
                            res.data[i].name+="("+res.data[i].countryCode+")";
                            tempData = res.data[i];
                            tempData.text =res.data[i].name;
                            tempData.id = res.data[i].countryCode;
                            tempData.isClude = isClude;
                            tempData.selected = true;
                            tempData.cType = "country";
                            //构造data数据
                            //"text":"United Kingdom(GB)","id":"GB","isClude":true,"selected":true,"cType":"country"
                            //去除重复。
                            data.countries.push(tempData);
                        }
                    });
                    kit.setTags(locSelect,res.data);
                    if(res.data.length == 0){
                        kit.alert3(I18N.getText('common', 'resultEmpty'));
                    }
                    locSelect.select2('close');
                    DATA.update('Location',index,data);
                    bindKeyDown();
                },function(){});
			    isCopy = false;
		});
		//#copy  end

        //回填历史数据
        processTemp(nodeId, index, data);
        function processTemp(nodeId, index, data){
            data.countries = processLocation(data.countries);
            data.cities = processLocation(data.cities);
            DATA.update(nodeId,index,data);
            var thearr = data.countries.concat(data.cities);
            kit.setTags(locSelect,thearr);
            //导入模板也校验地区个数
            checkCount();
            bindKeyDown();
        }
        /**
         * 处理模板数据
         */
        function processLocation(_datas){

            var newData = [];
            if (_datas){
                var excludeKeys = DATA.cache.adPublishConditionDetailCache.excludeKeys;
                var includeKeys = DATA.cache.adPublishConditionDetailCache.includeKeys;
                $.each(_datas, function(i, _data){

                    if ('country' == _data.cType){
                        _data.text = _data.name + '(' + _data.countryCode + ')';
                        _data.id = _data.countryCode;
                        _data.type = 'country';
                    } else {
                        _data.text = _data.name;
                        _data.id = _data.key + "";
                        _data.type = 'city';
                    }

                    //根据包括与不包括，与当前投放控制进行校验
                    var isAdd = false;
                    if (_data.isClude){
                        isAdd = includeKeys.length == 0  || $.inArray(_data.id, includeKeys) != -1;
                    } else {
                        isAdd = excludeKeys.length == 0  || $.inArray(_data.id, excludeKeys) != -1;
                    }

                    //去重
                    var idx = kit.find(newData,_data,"id","id");
                    if (isAdd && -1 == idx){
                        newData.push(_data);
                    }
                });
            }

            return newData;
        }
    }
});
